package cm.tl.pms.sys.controller;

import cm.tl.pms.common.entity.ResultMsg;
import cm.tl.pms.common.exception.CustomErrorException;
import cm.tl.pms.sys.entity.SysPower;
import cm.tl.pms.sys.entity.SysRole;
import cm.tl.pms.sys.entity.SysRolePower;
import cm.tl.pms.sys.service.ISysMenuService;
import cm.tl.pms.sys.service.ISysRolePowerService;
import cm.tl.pms.sys.service.ISysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 角色管理
 *
 * @author laker
 * @since 2021-08-11
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysMenuService sysMenuService;
    @Autowired
    ISysRolePowerService sysRolePowerService;

    /**
     * 查询列表
     *
     * @param current
     * @param size
     * @param roleName
     * @param enable
     * @return
     */
    @GetMapping
    public ResultMsg<Page<SysRole>> pageAll(@RequestParam(required = false, defaultValue = "1") long current,
                                            @RequestParam(required = false, defaultValue = "10") long size,
                                            String roleName, Boolean enable) {
        Page<SysRole> roadPage = new Page<>(current, size);
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(roleName), SysRole::getRoleName, roleName);
        queryWrapper.eq(!Objects.isNull(enable), SysRole::getEnable, enable);
        Page<SysRole> pageList = sysRoleService.page(roadPage, queryWrapper);
        return ResultMsg.successfulResult(pageList);
    }

    /**
     * 新增或者更新
     *
     * @param param
     * @return
     */
    @PostMapping
//    @SaCheckPermission("role.update")
    public ResultMsg saveOrUpdate(@RequestBody SysRole param) {
        sysRoleService.saveOrUpdate(param);
        return ResultMsg.successfulResult(param);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public ResultMsg get(@PathVariable Long id) {
        return ResultMsg.successfulResult(sysRoleService.getById(id));
    }


    @GetMapping("/allRoles")
    @ApiOperation(value = "查询全部角色")
    public ResultMsg getAll() {
        return ResultMsg.successfulResult(sysRoleService.list());
    }


    /**
     * 根据角色id查询角色权限
     * 如果角色是菜单角色 则剔除数据权限
     * 如果角色是数据权限 则剔除非数据权限
     *
     * @param roleId
     * @return
     */
    @GetMapping("/getRolePower")
    public ResultMsg getRolePower(Long roleId) {
        SysRole role = sysRoleService.getById(roleId);
        if (role == null) {
            throw new CustomErrorException("角色不存在");
        }
        List<SysPower> allPower = null;
//        // 菜单角色
//        if (role.getRoleType().equals(SysRole.ROLE_TYPE_MENU)) {
//            // 菜单
//            allPower = sysMenuService.list(Wrappers.<SysPower>lambdaQuery().in(SysPower::getType, 1));
//        }
//        else {
//            // 数据
//            allPower = sysMenuService.list(Wrappers.<SysPower>lambdaQuery().in(SysPower::getType, 0, 1, 3));
//        }

        List<SysRolePower> myPower = sysRolePowerService.list(Wrappers.<SysRolePower>lambdaQuery().eq(SysRolePower::getRoleId, roleId));
        List collect = myPower.stream().map(SysRolePower::getPowerId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            throw new CustomErrorException("角色 未配置 权限 ！");
        }
//        allPower.forEach(sysPower -> {
//            myPower.forEach(sysRolePower -> {
//                if (sysRolePower.getPowerId().equals(sysPower.getMenuId())) {
//                    sysPower.setCheckArr("1");
//                }
//            });
//        });
        allPower = sysMenuService.list(Wrappers.<SysPower>lambdaQuery().in(SysPower::getMenuId, collect));
        return ResultMsg.successfulResult(allPower);
    }

    /**
     * 保存角色权限数据
     *
     * @param roleId
     * @param powerIds
     * @return
     */
    @PutMapping("/saveRolePower")
//    @SaCheckPermission("role.update.power")
    public ResultMsg saveRolePower(Long roleId, String powerIds) {
        return ResultMsg.successfulResult(sysRolePowerService.saveRolePower(roleId, powerIds));
    }


    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
//    @SaCheckPermission("role.delete")
    public ResultMsg delete(@PathVariable Long id) {
        return ResultMsg.successfulResult(sysRoleService.removeById(id));
    }
}
